package com.azt.front.action.freemarker;

import com.azt.api.pojo.Category;
import com.azt.api.service.ProCategoryService;
import com.azt.front.utils.ContextUtil;
import com.azt.utils.FreemarkerUtils;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER;


/**
 * 首页全部分类静态化
 * Created by 张栋 on 2017/2/28 11:34
 */
@Component("all_cat")
public class AllCatsDirective implements TemplateDirectiveModel {

    @Autowired
    private ProCategoryService proCategoryService;

    String newtempname = "temp_index_category.html";
    String tempname = "index_category.html";
    @Override
    public void execute(Environment env, Map params, TemplateModel[] arg2, TemplateDirectiveBody body)
            throws TemplateException, IOException {
        //判断文件是否存在,不存在则生成并返回,存在则直接取
        boolean b = false;
        try {
            b = updateCategoryTemp();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(b){
            env.include("./front/category/"+newtempname, "UTF-8", true);
        }else{
            List<Category> categorys = proCategoryService.getAllCategories();
            Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>();
            paramWrap.put("categorys", DEFAULT_WRAPPER.wrap(categorys));
            DirectiveUtils.addParamsToVariable(env, paramWrap);
            env.include("./front/category/"+tempname, "UTF-8", true);
        }


    }




    volatile boolean creating =false;

    /**
     * 更新类目选择文件
     *
     *
     *
     * @author 张栋  2016年7月8日上午9:34:49
     */
    public boolean updateCategoryTemp() throws Exception {
        String tempath = ContextUtil.getSession().getServletContext().getRealPath("/WEB-INF/front/category");
        //返回true时,带表有生成的文件,可以直接用,否则需要动态创建
        if (!proCategoryService.proCategoryTempAuotCreate(-3)) {

            //自动状态下,不存在就生成
            java.io.File file = new java.io.File(tempath + "/" + newtempname);
            if (file.exists()) {
                //存在则不生成
                return true;
            }else{
                createHtml(tempath);
                return false;
            }
        } else {
            //为true时需要生成
            //非自动情况,直接生成
            createHtml(tempath);
            return false;
        }

    }




    //简单同步,超高并发下还是会重复生成
    public void  createHtml(final String tempath){
        if(!creating){
            creating=true;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        List<Category> categorys = proCategoryService.getAllCategories();
                        Map<String, Object> paramMap = new HashMap<>();
                        paramMap.put("categorys", categorys);
                        FreemarkerUtils.createHtml(tempath, tempname, paramMap, newtempname);
                    } catch (Exception e) {
                        java.io.File file = new java.io.File(tempath + "/" + newtempname);
                        if (file.exists()) {
                            file.delete();
                        }
                    }finally {
                        creating=false;
                    }
                }
            }).start();
        }
    }
}
